/*
 * Lab10A.cpp
 *  Created on: 2014-04-20
 *      Author: Anthony Varghese
 */

struct node{
	int item;
	node* next;
	node(int i, node* n): item(i), next(n){}
};

/*
 * Recursive add function
 * computes the sum of the data in the linked list
 *  starting from node p
 * precondition p != nullptr
 */
int add(const node* p){
	if (p==nullptr) return 0;
	if (p->next==nullptr) return p->item;
	return p->item + add(p->next);
}

/*
 * Recursive max function
 * computes the max of the data in the linked list
 *  starting from node p
 * precondition p != nullptr
 */
int max(const node* p){
	if (p==nullptr) return 0;
	if (p->next==nullptr) return p->item;

	int max_rest = max(p->next);
	if (p->item > max_rest)
		return p->item;
	else
		return max_rest;
}

#include <iostream>
using std::cout;
using std::endl;

/*
 * Recursive method to print a linked list in
 * "forward" order
 */
void forward_print(const node* p){
   if (p == nullptr) return;
   cout << p->item << " ";
   forward_print(p->next);
}

/*
 * Recursive method to print a linked list in
 * "reverse" order
 */
void reverse_print(const node* p){
   if (p == nullptr) return;
   cout << p->item << " ";
   reverse_print(p->next);
}

int main(){
	const node* A = new node( 6, new node( 2, new node( 18, new node( -4,
					  new node(5, new node(7, new node(1, nullptr)))))));

	cout << "Linked list contains ";
	forward_print( A ); cout << endl;

	cout << "   in reverse order: ";
	reverse_print( A ); cout << endl << endl;

	cout << "Sum of elements in linked list is: " << add( A ) << endl << endl;

	cout << "Max of elements in linked list is: " << max( A ) << endl << endl;
}
